﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //出库订单
    public class ProductOutController : Controller
    {
        private readonly IProductOutService productOutBillServiceImpl = ServiceLocator.Instance.GetService<IProductOutService>();	
        //
        // GET: /ProductIn/

        public ActionResult Index()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        [NoAuthorizated("Audit")]
        public ActionResult Audit(Guid billId, int isok)
        {
            try 
	        {
                var ids = new Dictionary<Guid, int>();
                ids.Add(billId, isok);
                var umodel = new UserModel();
                Guid uid=UserModel.GetLoginUserId(this.HttpContext);
                productOutBillServiceImpl.Audit(ids, uid, umodel.GetUserOrgID(uid));
            return Content("9");
	        }
	        catch (Exception)
	        {
		
		       // throw;
	        }
           
            return Content("0");
        }
        //反审核
        [NoAuthorizated("UnAudit")]
        public ActionResult UnAudit(Guid billId)
        {
            try
            {
                int stateCode = productOutBillServiceImpl.UnAudit(billId);
                return Content(stateCode.ToString());
            }
            catch (Exception)
            {

                // throw;
            }

            return Content("0");
        }

        [NoAuthorizated("Confirm")]
        public ActionResult Confirm(Guid billId)
        {
            try
            {
                string orgCode = Request.Form["HidOrgCode"];
                var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode.Trim());//初始化默认组织机构和仓库
                productOutBillServiceImpl.Confirm(new List<Guid>() { billId }, initSysData.Keys.First().Id);
                return Content("9");
            }
            catch (Exception)
            {

                // throw;
            }

            return Content("0");
        }
        #region 保存和提交统一入口
        [NoAuthorizated("AddAndConfirm")]
        [HttpPost]
        public ActionResult AddAndConfirm(ProductOutBillDto roductInBillDto)
        {
            bool isConfirm = Convert.ToBoolean(Request["isConfirm"]);

            Guid orgId=Guid.Empty;
            //订单已确认
            if (roductInBillDto.BillState > 0)
            {
                return new EmptyResult();
            }
            //保存(或更新)
            var contentRst = Add(roductInBillDto) as ContentResult;
            string actionResult = contentRst.Content.ToString();
            Guid tempId = Guid.Empty;
            if (Guid.TryParse(actionResult.ToString(), out tempId))
            {
                if (tempId.Equals(Guid.Empty))//有超过库存数量的单据
                {
                    return Content("-3");
                }
                roductInBillDto.ID = tempId;
              
            }
            else
            {
                return Content(actionResult.ToString());
            }
            //提交
            if (isConfirm)
            {


                if (roductInBillDto.ID != null && !roductInBillDto.ID.Equals(Guid.Empty))//记录已存在
                {

                    Confirm(roductInBillDto.ID);//提交
       
                }
            }
            return Content("9");
        }
        #endregion
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = productOutBillServiceImpl.GetProductOutBill(id);
            BindSP(billModel.IsVoucher);
            return View(billModel);
        }
        #endregion
        #region 添加出库单
         [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode, Guid? id)
        {
            ProductOutBillDto billModel = null;
           
            if (id == null || !id.HasValue)
            {
                var NO = new BusinessBillNoCreator().CreateOutNextNO();

                var initSysData = DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                var wareHouse = initSysData.Values.FirstOrDefault();

                billModel = new ProductOutBillDto
                {
                    ProductSellBillNo = NO,
                    StorehouseName = wareHouse.StorehouseName,
                    StorehouseID = wareHouse.Id
                };
                ViewBag.BillId = "";
            }
            else
            {
                Guid billId ;
                Guid.TryParse(id.ToString(),out billId);
               billModel= productOutBillServiceImpl.GetProductOutBill(billId);
               ViewBag.BillId = billId.ToString();
            }
            ViewBag.TempId = Guid.NewGuid();
            ViewBag.orgCode = orgCode;
            BindSP(billModel.IsVoucher);
            billModel.SellTime = DateTime.Today;
            return View(billModel);
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ProductOutBillDto roductInBillDto)
        {
            #region 弹出框数据获取
            var model = new ProductOutBillModel();
            //仓库ID
            var whId=model.GetRequestFormValues(this.HttpContext,"StorehouseName_val");
            if(!Guid.Empty.Equals(whId))
            {
              roductInBillDto.StorehouseID =whId;
            }
            //负责人ID
            var sellerid = model.GetRequestFormValues(this.HttpContext, "SellerName_val"); //SenderName
            if (!Guid.Empty.Equals(sellerid))
            {
                roductInBillDto.SellorID = sellerid;
            }
            //送货人ID 
            var sendid = model.GetRequestFormValues(this.HttpContext, "SenderName_val"); //SenderName
            if (!Guid.Empty.Equals(sendid))
            {
                roductInBillDto.SenderId = sendid;
            }
            //客户ID 
            //var clientid = model.GetRequestFormValues(this.HttpContext, "ClientName_val"); //SenderName
            //if (!Guid.Empty.Equals(clientid))
            //{
            //    roductInBillDto.ClientID = clientid;
            //}
            #endregion
            #region 主数据行处理
            roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
            roductInBillDto.UpdateID = roductInBillDto.CreateID;
            int isVocher=0;
            if (Int32.TryParse(Request.Form["IsVoucher"].ToString(), out isVocher))
            {
                roductInBillDto.IsVoucher = isVocher;
            }
            else
            {
                roductInBillDto.IsVoucher = 0 ;
            }
	        #endregion
            #region 明细行数据处理
		 

            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.GetProductItems(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("-1");//明细行异常
            }
          //  detailItems.Each(item => { item.ProductInBillID = roductInBillDto.ID; if (item.ID == item.ProductInBillID && item.ProductInBillID != roductInBillDto.ID&&item.ID!=null&&!item.ID.Equals(Guid.Empty)) { item.ID = Guid.Empty; } });
	        #endregion

            #region 数据验证
            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
                return Content("-1");
            }
            roductInBillDto.ClientOrderNo = roductInBillDto.ClientOrderNo == null ? "" : roductInBillDto.ClientOrderNo;
            #endregion
            if (ModelState.IsValid)
            {
                try
                {

                  var tempId=  productOutBillServiceImpl.AddOrUpdateProductOutBill(roductInBillDto, detailItems);//若存在即更新
                  return Content(tempId.ToString());
                }
                catch (Exception ex)
                {
                    return Content("-2");
                }
               
               // ViewBag.PostState = 9;
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 删除订单明细（假删除）
        [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId,string ids)
        {
            if (ids!="all"&&ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                productOutBillServiceImpl.ConvertProductOutBillDeleteState(billId, guidIds);
                return Content("9");
            }
            else
            {
                productOutBillServiceImpl.ConvertProductOutBillDeleteState(billId);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 获取出库单列表数据
        //暂时获取所有数据
        [NoAuthorizated("GetJsonOfProductOutBills")]
        public ActionResult GetJsonOfProductOutBills()
        {
            #region  EF的查询，效率低下，故暂时放弃不用
            /*
            var productBills = productOutBillServiceImpl.GetProductOutBills(1, 100);
            if (productBills != null && productBills .Count() != 0)
            {
                var jsonResult = productBills.Select(u => { u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                         return u; 
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"10\"}";
                return Content(target);
            }
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetProductSellBills(this.HttpContext));
        }
        /// <summary>
        /// 根据出库单ID，获得出库单所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
       [NoAuthorizated("GetJsonOfProductOutBillDetails")]
        public ActionResult GetJsonOfProductOutBillDetails(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            //var productInBillDetails = productOutBillServiceImpl.GetProductOutBillDetails(billId).Where(p => p.Deleted == 0).ToList();
            //if (productInBillDetails != null && productInBillDetails.Count() != 0)
            //{
            //    var jsonResult = productInBillDetails;
            //    var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //    target = "{\"Rows\":" + target + ",\"Total\":\"" + productInBillDetails.Count() + "\"}";
            //    return Content(target);
            //}
            // return Content("");
            #endregion
             if (!billId.Equals(Guid.Empty))
             {
                 return Content(new BLLQuery().GetProductSellDetails(billId));
             }
             else
             {
                 return Content("");
             }
        }
        #endregion
        #region 深圳业务
        public ActionResult SZIndex()
        {
            ViewBag.orgCode = SystemConfig.ShengZhenCode;
            return View("Index");
        }
        #endregion
        #region 票据方式
        private void BindSP(int isTrue)
        {
            var lst = new List<SelectListItem> { 
                 new SelectListItem{  Text="是", Value="1" },
                  new SelectListItem{  Text="否", Value="0" },
            };

            foreach (var item in lst)
            {
                if (item.Value == isTrue.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }
            ViewBag.IsVoucherList = lst;

        }
        #endregion

        #region 打印销售单据
         [NoAuthorizated("Print")]
        public ActionResult Print(Guid billId)
        {
            var billAndDetails = productOutBillServiceImpl.GetBillAndDetails(billId); //获得主表数据和从表数据
            var printModel = new ProductOutPrint { ProductOutBillDto = billAndDetails.Keys.FirstOrDefault(),
                                                   ProductOutBillDetailsDto = billAndDetails.Values.FirstOrDefault()
            };


            if (printModel.ProductOutBillDetailsDto != null && printModel.ProductOutBillDetailsDto.Count() != 0)
            {
                printModel.ProductOutBillDto.SellMoney = 0m;
                foreach (var t in printModel.ProductOutBillDetailsDto)
                {
                    if (t.Deleted != 1)
                    {
                        printModel.ProductOutBillDto.SellMoney += Math.Round(((decimal)t.SellAmount * t.SellPrice), 2);
                    }
                }
            }
            return View(printModel);
            //return Content(" 这个是测试数据");
        }

        #endregion
    }
   
}
